#define  _CRT_SECURE_NO_WARNINGS
// class Solution {
// public:
//     vector<string> topKFrequent(vector<string>& words, int k) {
//         map<string, int> hash;
//         for(auto e : words) hash[e]++;

//         vector<pair<string, int>> tmp;
//         for(auto& e : hash) tmp.push_back(e);

//         stable_sort(tmp.begin(), tmp.end(), 
//         [](pair<string, int> n1, pair<string, int> n2)
//         { 
//             return n1.second > n2.second;
//         });

//         vector<string> ret;
//         for(auto& [x, y] : tmp) 
//             if(k--) ret.push_back(x); 
//             else break;
//         return ret;
//     }
// };
class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> hash;
        for (auto e : words) hash[e]++;

        auto cmp = [](pair<string, int> p1, pair<string, int> p2)
            {
                return p1.second == p2.second ? p1.first < p2.first : p1.second > p2.second;
            };

        priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(cmp)> pq;
        for (auto e : hash)
        {
            pq.push(e);
            if (pq.size() > k)pq.pop();
        }

        vector<string> ret(k);
        while (pq.size())
        {
            ret[--k] = pq.top().first;
            pq.pop();
        }
        return ret;
    }
};